package com.penghaisoft.microwms.product.service.impl;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.ProHandOut;
import com.penghaisoft.microwms.common.data.model.ProHandOutPrint;
import com.penghaisoft.microwms.common.data.model.ProHandOutSn;
import com.penghaisoft.microwms.common.dto.ProHandOutDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.product.dao.*;
import com.penghaisoft.microwms.product.service.IProHandOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 * 业务逻辑实现类
 * </p>
 *
 * @author
 * @createDate
 **/
@Service("proHandOutService")
public class ProHandOutServiceImpl extends BaseService implements IProHandOutService {
	@Autowired
	private ProHandOutMapper proHandOutMapper;

	@Autowired
	private ProStorageSnMapper proStorageSnMapper;

	@Autowired
	private ProHandOutSnMapper proHandOutSnMapper;

	@Autowired
	private MdPurchaseMapper mdPurchaseMapper;

	@Autowired
	private ProBarcodeMapper proBarcodeMapper;

	/**
	 * 新增记录
	 *
	 * @param
	 * @return
	 */
	@Override
	public Resp create(ProHandOut proHandOut) {
		proHandOutMapper.create(proHandOut);
		return success();
	}

	/**
	 * 删除记录（逻辑删除）
	 *
	 * @param
	 * @return
	 */
	@Override
	public Resp delete(ProHandOut proHandOut) {
		proHandOutMapper.delete(proHandOut);
		return success();
	}

	/**
	 * 查询列表
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public Pager<ProHandOut> findListByCondition(int page, int rows, ProHandOut condition) {
		Pager<ProHandOut> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = proHandOutMapper.queryCount(condition);
		List<ProHandOut> records = new ArrayList<ProHandOut>();
		if (size > 0) {
			records = proHandOutMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * 查询单条
	 *
	 * @param id
	 * @return
	 */
	@Override
	public ProHandOut findById(String id) {
		return proHandOutMapper.queryById(id);
	}

	/**
	 * 修改记录
	 *
	 * @param
	 * @return
	 */
	@Override
	public Resp update(ProHandOut proHandOut) {
		proHandOutMapper.updateBySelect(proHandOut);
		return success();
	}

	@Override
	public Resp loadBill(ProHandOut proHandOut) {
		Resp resp = new Resp();

		proHandOut.setActiveFlag("1");
		List<ProHandOut> list = proHandOutMapper.queryByAny(proHandOut);

		if (list == null || list.isEmpty()) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("该手工出库单号不存在");
		} else {
			if (list.get(0).getHandOutStatus().equals("2")) {
				resp.setCode(Constant.SUCCESS);
				resp.setMsg("该手工出库单已经发货完成！");
				return resp;
			}
			for (ProHandOut temp : list) {
				if (temp.getHandOutStatus().equals("1") || temp.getHandOutStatus().equals("3")
						|| temp.getHandOutStatus().equals("0")) {
					resp.setCode(Constant.SUCCESS);
					resp.setMsg("提单成功！");
					return resp;
				}
			}
//			resp.setCode(Constant.FAIL);
//			resp.setMsg("该手工出库单未通过审核！");
//			return resp;
		}
		return resp;
	}

	@Override
	public List<ProHandOut> queryListByAny(ProHandOut condition) {
		return proHandOutMapper.queryByAny(condition);
	}

	/* @Title: handOutScanBarcode 
	 * @Description: 出库扫码
	 * @author yanggm
	 * @date 2018年8月27日 上午9:58:32 
	 */
	@Override
	public TransResult handOutScanBarcode(ProHandOutDto proHandOutDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		if (isOutput(proHandOut)) {
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单已经出库完成！");
			return result;
		}
		Date now = new Date();

		ProStorageSn proStorageSn = new ProStorageSn();
		proStorageSn.setBarcode(proHandOutDto.getBarcode());
		proStorageSn.setActiveFlag("1");
		//根据条码查找 仓库成品
		List<ProStorageSn> storageList = proStorageSnMapper.queryByAny(proStorageSn);
		if (storageList == null || storageList.isEmpty()) {
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码不在库存中");
			return result;
		} else if (storageList.size() > 1) {
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码重复");
			return result;
		} else {
			ProStorageSn proStorageSnTemp = storageList.get(0);
//        	0：可用 1：冻结 2：已出库 
			if (proStorageSnTemp.getBarcodeStatus() == null) {
				result.setCode(Constant.FAIL);
				result.setMsg("该成品条码状态为空");
				return result;
			} else if (proStorageSnTemp.getBarcodeStatus().equals("2")) {
				result.setCode(Constant.FAIL);
				result.setMsg("该成品条码已出库");
				return result;
			} else if (proStorageSnTemp.getBarcodeStatus().equals("1")) {
				result.setCode(Constant.FAIL);
				result.setMsg("该成品条码已冻结");
				return result;
			} else if (proStorageSnTemp.getBarcodeStatus().equals("0")) {
				ProHandOutSn proHandOutSn = new ProHandOutSn();
				proHandOutSn.setBarcode(proHandOutDto.getBarcode());
				proHandOutSn.setActiveFlag("1");
				List<ProHandOutSn> handOutSnList = proHandOutSnMapper.queryByAny(proHandOutSn);
				if (!handOutSnList.isEmpty() && handOutSnList != null) {
					result.setCode(Constant.FAIL);
					result.setMsg("该成品条码已扫描，不能再次扫描!");
					return result;
				} else {
//					ProHandOut proHandOut = new ProHandOut();
//					proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
					proHandOut.setModel(proStorageSnTemp.getModel());
					proHandOut.setWaCode(proStorageSnTemp.getWaCode());
					proHandOut.setGrade(proStorageSnTemp.getGrade());
					proHandOut.setLevel(proStorageSnTemp.getLevel());
					proHandOut.setType(proStorageSnTemp.getType());
					proHandOut.setActiveFlag("1");
					List<ProHandOut> handOutList = proHandOutMapper.queryByAny(proHandOut);
					if (handOutList.isEmpty() || handOutList == null) {
						result.setCode(Constant.FAIL);
						result.setMsg("该条码不是出库单所需!");
						return result;
					} else {
						ProHandOut handOutTemp = handOutList.get(0);
//						if("0".equals(handOutTemp.getHandOutStatus())){
//							result.setCode(Constant.FAIL);
//							result.setMsg("该条码不是当前出库单所需!");
//							return result;
//						}
						List<ProHandOut> rtnList = new ArrayList<>();
//						所需数量  实发数量  实发重量
						BigDecimal requireAmount = handOutTemp.getRequireAmount() == null ? BigDecimal.ZERO : handOutTemp.getRequireAmount();
						BigDecimal realAmount = handOutTemp.getRealAmount() == null ? BigDecimal.ZERO : handOutTemp.getRealAmount();
//						BigDecimal weight = handOutTemp.getWeight();//handOutTemp.getWeight()==null?BigDecimal.ZERO:
						if (realAmount.compareTo(requireAmount) == 0
								|| requireAmount.compareTo(realAmount) < 0) {
							result.setCode(Constant.FAIL);
							result.setMsg("该型号已经扫码完成，无需继续扫码!");
							return result;
						} else {
//							0新建 1出库中 2出库完成
							handOutTemp.setHandOutStatus("1");
							handOutTemp.setLastModifiedBy(proHandOutDto.getLoginName());
							handOutTemp.setGmtModified(now);
//							更新数量的sql 去掉realAmout和weight的更新
							handOutTemp.setRealAmount(null);
							handOutTemp.setWeight(null);

							handOutTemp.setRealAmountAdd(new BigDecimal(1));
							realAmount = realAmount.add(new BigDecimal(1));
							handOutTemp.setWeightAdd(proStorageSnTemp.getWeight());
						}
						Integer rtVal = proHandOutMapper.updateBySelect(handOutTemp);
						if (rtVal != 1) {
							throw new RuntimeException("扫描条码失败，更新条数存在问题!");
						}
//						该实发数量、实发重量只是提供给手持显示，后台sql加
						handOutTemp.setRealAmount(realAmount);
						handOutTemp.setWeight(proStorageSnTemp.getWeight());

						//修改库存条码状态
						proStorageSnTemp.setBarcodeStatus("2");
						proStorageSnTemp.setUserDefined4("0");
						proStorageSnTemp.setLastModifiedBy(proHandOutDto.getLoginName());
						proStorageSnTemp.setGmtModified(now);
						int rtVal02 = proStorageSnMapper.updateByBarcodeStatus0(proStorageSnTemp);
						if (rtVal02 != 1) {
							throw new RuntimeException("该条码不在库中，或已被冻结！");
						}

//						返回给手持数据
						rtnList.add(handOutTemp);
						result.setList(rtnList);

						ProHandOutSn handOutSnInsertOb = new ProHandOutSn();
						handOutSnInsertOb.setHandOutNo(handOutTemp.getHandOutNo());
						handOutSnInsertOb.setBarcode(proHandOutDto.getBarcode());
						handOutSnInsertOb.setModel(handOutTemp.getModel());
						handOutSnInsertOb.setType(handOutTemp.getType());
						handOutSnInsertOb.setProductName(proStorageSnTemp.getProductName());
						handOutSnInsertOb.setDensity(proStorageSnTemp.getDensity());
						handOutSnInsertOb.setSpec(proStorageSnTemp.getSpec());
						handOutSnInsertOb.setWeight(proStorageSnTemp.getWeight());
						handOutSnInsertOb.setUnit(proStorageSnTemp.getUnit());
						handOutSnInsertOb.setMachineNumber(proStorageSnTemp.getMachineNumber());
						handOutSnInsertOb.setGrade(proStorageSnTemp.getGrade());
						handOutSnInsertOb.setLevel(proStorageSnTemp.getLevel());
						handOutSnInsertOb.setWaCode(proStorageSnTemp.getWaCode());
						handOutSnInsertOb.setWlCode(proStorageSnTemp.getWlCode());
						handOutSnInsertOb.setActiveFlag("1");
						handOutSnInsertOb.setGmtCreate(now);
						handOutSnInsertOb.setCreateBy(proHandOutDto.getLoginName());
						proHandOutSnMapper.create(handOutSnInsertOb);
					}
				}
			}
		}
		return result;
	}

	/* @Title: handOutComplete 
	 * @Description: 出库完成，确认
	 * @author yanggm
	 * @date 2018年8月27日 上午10:27:24 
	 */
	@Override
	public TransResult handOutComplete(ProHandOutDto proHandOutDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		if (isOutput(proHandOut)) {
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单已经出库完成！");
			return result;
		}
		Date now = new Date();

//		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setActiveFlag("1");
//		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		List<ProHandOut> handOutList = proHandOutMapper.queryByAny(proHandOut);
		if (handOutList == null || handOutList.isEmpty()) {
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单不存在！");
			return result;
		} else {
			for (ProHandOut tmp : handOutList) {
				BigDecimal requireAmount = tmp.getRequireAmount() == null ? BigDecimal.ZERO : tmp.getRequireAmount();
				BigDecimal realAmount = tmp.getRealAmount() == null ? BigDecimal.ZERO : tmp.getRealAmount();
				if (requireAmount.compareTo(realAmount) > 0) {
					result.setCode(Constant.FAIL);
					result.setMsg("该出库单未扫码完毕！");
					return result;
				} else if (requireAmount.compareTo(realAmount) < 0) {
					result.setCode(Constant.FAIL);
					result.setMsg("该出库单扫码数量超过需求数量!");
					return result;
				}
			}
			ProHandOutSn proHandOutSn = new ProHandOutSn();
			proHandOutSn.setHandOutNo(proHandOutDto.getHandOutNo());
			ProHandOutSn handOutSn = proHandOutSnMapper.selectBeginEndScanTime(proHandOutSn);

			ProHandOut handOutUpdateOb = new ProHandOut();
			handOutUpdateOb.setHandOutNo(proHandOutDto.getHandOutNo());
			handOutUpdateOb.setScanTimeBegin(handOutSn.getScanTimeBegin());
			handOutUpdateOb.setScanTimeEnd(handOutSn.getScanTimeEnd());
			handOutUpdateOb.setHandOutStatus("2");
			handOutUpdateOb.setLastModifiedBy(proHandOutDto.getLoginName());
			handOutUpdateOb.setGmtModified(now);
			proHandOutMapper.updateByHandOutNo(handOutUpdateOb);
//			货主、车牌、出库经办人 等传入明细表
			ProHandOut temp = handOutList.get(0);
			proHandOutSn.setUserDefined1(temp.getUserDefined1());
			proHandOutSn.setUserDefined2(temp.getUserDefined2());
			proHandOutSn.setUserDefined4(temp.getUserDefined4());
			proHandOutSn.setUserDefined5(proHandOutDto.getLoginName());
			proHandOutSnMapper.updateByOutNo(proHandOutSn);
//			生产类型改为不开发票：B
			proBarcodeMapper.updateByHandOutNo(proHandOutDto.getHandOutNo());
		}
		return result;
	}

	/* @Title: handOutDelBarcode 
	 * @Description: 退扫
	 * @author yanggm
	 * @date 2018年8月27日 上午11:31:51 
	 */
	@Override
	public TransResult handOutDelBarcode(ProHandOutDto proHandOutDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		if (isOutput(proHandOut)) {
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单已经出库完成！");
			return result;
		}
		Date now = new Date();

		ProStorageSn proStorageSn = new ProStorageSn();
		proStorageSn.setBarcode(proHandOutDto.getBarcode());
//    	0：可用 1：冻结 2：已出库 3：抽检冻结
		proStorageSn.setBarcodeStatus("2");
		proStorageSn.setActiveFlag("1");
		List<ProStorageSn> storageSnList = proStorageSnMapper.queryByAny(proStorageSn);
		if (storageSnList == null || storageSnList.isEmpty()) {
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码未出库!");
			return result;
		} else if (storageSnList.size() > 1) {
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码重复");
			return result;
		} else {
			ProStorageSn storageSnTemp = storageSnList.get(0);

			ProHandOutSn proHandOutSn = new ProHandOutSn();
			proHandOutSn.setHandOutNo(proHandOutDto.getHandOutNo());
			proHandOutSn.setBarcode(proHandOutDto.getBarcode());
			proHandOutSn.setActiveFlag("1");
			List<ProHandOutSn> handOutSnList = proHandOutSnMapper.queryByAny(proHandOutSn);
			if (handOutSnList == null || handOutSnList.isEmpty()) {
				result.setCode(Constant.FAIL);
				result.setMsg("该条码不在本出库单下!");
				return result;
			} else {
				ProHandOutSn handOutSnTemp = handOutSnList.get(0);

//            	 ProHandOut proHandOut = new ProHandOut();
				proHandOut.setActiveFlag("1");
//            	 proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
				proHandOut.setModel(storageSnTemp.getModel());
				proHandOut.setWaCode(storageSnTemp.getWaCode());
				proHandOut.setGrade(storageSnTemp.getGrade());
				proHandOut.setLevel(storageSnTemp.getLevel());
				List<ProHandOut> handOutList = proHandOutMapper.queryByAny(proHandOut);
				if (handOutList == null || handOutList.isEmpty()) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码与出库单所需型号、仓库、等级或级别不一致!");
					return result;
				} else {
					ProHandOut handOutTemp = handOutList.get(0);
					List<ProHandOut> rtList = new ArrayList<>();
//            		 // 需求数量
//                     BigDecimal requireAmount = handOutTemp.getRequireAmount() ==null ? BigDecimal.ZERO : handOutTemp.getRequireAmount();
					// 已发数量
					BigDecimal realAmount = handOutTemp.getRealAmount() == null ? BigDecimal.ZERO : handOutTemp.getRealAmount();
//                     // 已发重量
//                     BigDecimal weight = handOutTemp.getWeight();//handOutTemp.getWeight()==null?BigDecimal.ZERO:
// 					0新建 1出库中 2出库完成
					handOutTemp.setHandOutStatus("1");
					handOutTemp.setLastModifiedBy(proHandOutDto.getLoginName());
					handOutTemp.setGmtModified(now);
//                   更新时去掉realAmount和weight的更新
					handOutTemp.setRealAmount(null);
					handOutTemp.setWeight(null);

					handOutTemp.setRealAmountDel(new BigDecimal(1));
					realAmount = realAmount.subtract(new BigDecimal(1));
					handOutTemp.setWeightDel(storageSnTemp.getWeight());
//                     weight = weight.subtract(storageSnTemp.getWeight());
					Integer rtVal = proHandOutMapper.updateBySelect(handOutTemp);
					if (rtVal != 1) {
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}

// 					该实发数量、实发重量只是提供给手持显示，后台sql加
					handOutTemp.setRealAmount(realAmount);
					handOutTemp.setWeight(storageSnTemp.getWeight());
// 					返回给手持数据
					rtList.add(handOutTemp);
					result.setList(rtList);

					handOutSnTemp.setActiveFlag("0");
					handOutSnTemp.setLastModifiedBy(proHandOutDto.getLoginName());
					handOutSnTemp.setGmtModified(now);
					Integer rtVal1 = proHandOutSnMapper.updateBySelect(handOutSnTemp);
					if (rtVal1 != 1) {
						throw new RuntimeException("退码失败，更新条数存在问题");
					}
// 					0：可用 1：冻结 2：已出库 3：抽检冻结
					storageSnTemp.setBarcodeStatus("0");
					storageSnTemp.setLastModifiedBy(proHandOutDto.getLoginName());
					storageSnTemp.setGmtModified(now);
					Integer rtVal20 = proStorageSnMapper.updateByBarcodeStatus2(storageSnTemp);
					if (rtVal20 != 1) {
						throw new RuntimeException("退码失败，更新条数存在问题!");
					}
				}
			}
		}
		return result;
	}

	/**
	 * 根据前段传过来的型号 数量 创建手工出库单
	 */
	@Override
	public Resp insert(List<ProHandOut> list, String handOutNo, String loginName) {
		Date date = new Date();
		HashSet<String> allSet = new HashSet<String>();
		for (int i = 0; i < list.size(); i++) {
			ProHandOut handOut = list.get(i);

			StringBuffer uniqueStr = new StringBuffer("");
			uniqueStr.append(handOut.getModel());
			uniqueStr.append(handOut.getWaCode());
			uniqueStr.append(handOut.getGrade());
			uniqueStr.append(handOut.getLevel());
			if (allSet.contains(uniqueStr.toString())) {
				Resp resp = new Resp();
				resp.setCode(Constant.FAIL);
				resp.setMsg("选择的型号" + handOut.getModel() + "、等级" + handOut.getGrade()
						+ "、级别" + handOut.getLevel() + "、仓库" + handOut.getWaCode() + "重复");
				return resp;
			} else {
				allSet.add(uniqueStr.toString());
			}
		}
		for (int i = 0; i < list.size(); i++) {
//			ProHandOut hand = new ProHandOut();
			ProHandOut hand = list.get(i);
			//写入 根据页面传来的值写入
			hand.setHandOutNo(handOutNo);
			hand.setActiveFlag("1");
			hand.setGmtCreate(date);
			hand.setCreateBy(loginName);
			hand.setGmtModified(date);
			hand.setLastModifiedBy(loginName);
			hand.setHandOutStatus("0");
			hand.setRealAmount(new BigDecimal(0));
			proHandOutMapper.create(hand);
		}
		return success();
	}

	@Override
	public Resp updateByNo(ProHandOut proHandOut) {
		proHandOutMapper.updateByHandOutNo(proHandOut);
		return success();
	}

	@Override
	public List<ProHandOut> queryListByStatus(ProHandOut condition) {
		return proHandOutMapper.queryByStatus(condition);
	}

	//	是否出库完成
	public boolean isOutput(ProHandOut proHandOut) {
		proHandOut.setActiveFlag("1");
		List<ProHandOut> list = proHandOutMapper.queryByAny(proHandOut);
		if ("2".equals(list.get(0).getHandOutStatus())) {
			return true;
		}
		return false;
	}

	@Override
	public TransResult queryPrint(ProHandOut condition) {
		TransResult result = new TransResult();
		ProHandOutPrint print = proHandOutMapper.queryPrint(condition);
		print.setUserDefined1(mdPurchaseMapper.queryNameByCode(print.getUserDefined1()));
		print.setProHandOutSns(proHandOutSnMapper.queryListPrint(condition));
		result.setCode(Constant.SUCCESS);
		List<ProHandOutPrint> list = new ArrayList<>();
		list.add(print);
		result.setList(list);
		return result;
	}


	@Override
	public TransResult handToSell(ProHandOut proHandOut) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);

		// 把手工出库表中的数据导入销售出库表中
		ProHandOut handOut = new ProHandOut();
		handOut.setHandOutNo(proHandOut.getHandOutNo());
		proHandOutMapper.insertSell(handOut);

		// 把手工出库明细表中的数据导入销售出库明细表中
		ProHandOutSn snTmp = new ProHandOutSn();
		snTmp.setHandOutNo(proHandOut.getHandOutNo());
		proHandOutSnMapper.insertSellSn(snTmp);

		// 手工出库明细表中将数据设为无效
		snTmp.setActiveFlag("0");
		proHandOutSnMapper.updateByOutNo(snTmp);

		// 条码表中将条码的生产类型标记为开票类型
		proHandOutMapper.updateProBarcodeA(proHandOut);


		// 手工出库表中将原数据设为无效并记录转销售出库
		handOut.setActiveFlag("0");
		handOut.setUserDefined9("转销售");
		proHandOutMapper.updateByHandOutNo(handOut);
		return result;
	}

}
